import axios from 'axios';
import { Message } from 'element-ui';
import store from './store';
import { authService } from './services';
import router from './router';


function showErrorMessage(message) {
  Message.error({ showClose: true, message: message, customClass:'zZindex' });
}

// axios.defaults.baseURL = 'http://125.124.170.40:8888';

axios.interceptors.request.use(
  (config) => {
    const { disableLoading } = config;
    if (!disableLoading) {
      store.dispatch('incrementLoadingRef');
    }
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['token'] = token;
    }
    return config;
  },
  (error) => {
    if (process.env.NODE_ENV !== 'production') {
      // eslint-disable-next-line
      console.log(error);
    }
    return Promise.reject(error);
  },
);

axios.interceptors.response.use(
  (response) => {
    const { disableLoading } = response.config;
    if (!disableLoading) {
      store.dispatch('decrementLoadingRef');
    }
    if (process.env.NODE_ENV !== 'production') {
      // eslint-disable-next-line
       console.log(response);
    }
    const { code, msg, data } = response.data;
    if (code !== 200) {
      if (process.env.NODE_ENV !== 'production') {
        showErrorMessage(`${msg} ${code}`);
      } else {
        showErrorMessage(msg);
      }
      return Promise.reject(data);
    }
    return data;
  },
  (error) => {
    const { disableLoading } = error.config;
    if (!disableLoading) {
      store.dispatch('decrementLoadingRef');
    }
    if (process.env.NODE_ENV !== 'production') {
      // eslint-disable-next-line
      console.log(JSON.stringify(error));
    }
    if (error.response) {
      const { status } = error.response;
      if (status === 401) {
        authService.logout().then(() => {
          router.push({ name: 'login' });
        });
      } else {
        const message = '服务器异常';
        showErrorMessage(`${message} ${error.response.status}`);
      }
    } else if (error.request) {
      showErrorMessage(error.request);
    } else {
      showErrorMessage(error.message);
    }
    return Promise.reject(error);
  },
);

export default axios;
